package com.springboot.template.service.impl;

import com.springboot.template.service.ICryptoService;
import com.springboot.template.utils.RSAUtil;
import com.springboot.template.utils.redis.RedisCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Zhang Yu
 * @description: TODO
 * @date 2024/5/27 14:43
 */
@Service
public class CryptoServiceImpl implements ICryptoService {

    @Autowired
    RedisCache redisCache;

    private final String REDIS_CACHE_KEY_SECURITY = "redis_cache_key_security";
    private final String REDIS_CACHE_KEY_SECURITY_SUB_RSA_PUBLIC = "rsa_public";
    private final String REDIS_CACHE_KEY_SECURITY_SUB_RSA_PRIVATE = "rsa_private";

    @Override
    public String rsaServerPublicKey(String userId) {
        String redisCacheRsaPublicKey = REDIS_CACHE_KEY_SECURITY + ":" + REDIS_CACHE_KEY_SECURITY_SUB_RSA_PUBLIC;
        //1.判断是否有公钥和私钥
        String rsaPublicKey = redisCache.getCacheObject(redisCacheRsaPublicKey);
        //2.有的话直接获取公钥
        if (!StringUtils.isBlank(rsaPublicKey)) {

        }else {
            //3.没有的话生成公钥和私钥,存储redis中
            Map<String, String> keyMap = RSAUtil.generateKey();
            rsaPublicKey = keyMap.get("publicKeyStr");
            String privateKeyStr = keyMap.get("privateKeyStr");
            redisCache.setCacheObject(redisCacheRsaPublicKey,rsaPublicKey);
            redisCache.setCacheObject(REDIS_CACHE_KEY_SECURITY_SUB_RSA_PRIVATE,privateKeyStr);
        }
        return rsaPublicKey;
    }

    @Override
    public String addRSAServerPublicKey(String userId, String publicKey, String privateKey) {
        return null;
    }
}
